<template>
  <div class="app-container">

    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="退料单号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入退料单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="退料单名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入退料单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="返修工单" prop="repairCode">
        <el-input
          v-model="queryParams.repairCode"
          placeholder="请输入返修工单"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="返修工单" prop="tenantId">
        <el-input
          v-model="queryParams.tenantId"
          placeholder="请输入返修工单"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rr:requisition:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['rr:requisition:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rr:requisition:remove']"
        >删除</el-button>
      </el-col>-->
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['rr:requisition:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requisitionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退料单号" align="center" prop="orderCode" >
        <template slot-scope="scope">
          <el-button
              type="text"
              @click="handleView(scope.row)"
              v-hasPermi="['rr:requisition:query']"
          >{{scope.row.orderCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="退料单名称" align="center" prop="orderName" />
<!--      <el-table-column label="返修单id" align="center" prop="repairId" />-->
      <el-table-column label="返修工单" align="center" prop="repairCode" />
      <el-table-column label="退料日期" align="center" prop="orderDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center"  fixed="right" width="180">
        <template slot-scope="scope">

            <el-button
              size="mini"
              type="text"
              icon="el-icon-video-play"
              @click="handleExecute(scope.row)"
              v-if="scope.row.status =='CONFIRMED'"
              v-hasPermi="['rr:requisition:execute']"
            >执行出库</el-button>


            <el-button
                size="mini"
                type="text"
                icon="el-icon-circle-check"
                v-if="scope.row.status =='PREPARE'"
                @click="handleConfirme(scope.row)"
                v-hasPermi="['rr:requisition:edit']"
            >确认</el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="scope.row.status =='PREPARE'"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['rr:requisition:edit']"
            >修改</el-button>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="scope.row.status =='PREPARE'"
              @click="handleDelete(scope.row)"
              v-hasPermi="['rr:requisition:remove']"
            >删除</el-button>

            <el-button
                size="mini"
                type="primary"
                icon="el-icon-printer"
                v-if="scope.row.status =='FINISHED'"
                @click="handlePrint(scope.row)"
            >打印</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改返修退料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="退料单号" prop="orderCode">
              <el-input v-model="form.orderCode" placeholder="请输入退料单号" :disabled="optType !== 'add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退料单名称" prop="orderName">
              <el-input v-model="form.orderName" placeholder="请输入退料单名称"  :disabled="optType == 'view'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="返修工单" prop="repairCode">
              <el-input v-model="form.repairCode" placeholder="请输入返修工单" readonly  v-if = "optType == 'add' || optType =='edit'">
                <el-button slot="append" v-if="optType != 'view'" icon="el-icon-search" @click="handleRepairSelect" ></el-button>
              </el-input>
              <el-input v-model="form.repairCode" placeholder="请输入返修工单" disabled  v-else />
            </el-form-item>
            <RepairSelect ref="repairSelect" @onSelected="onRepairSelected"></RepairSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退料日期" prop="orderDate">
              <el-date-picker clearable  style="width: 100%"
                              v-model="form.orderDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :default-value="new Date()"
                              :disabled="optType == 'view'"
                              placeholder="请选择退料日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="optType == 'view'"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider content-position="center" v-if="form.orderId !=null">物料信息</el-divider>
      <el-card shadow="always" v-if="form.orderId !=null" class="box-card">
        <ReturnLine ref="line" :orderId="form.orderId" :optType="optType" @change="getItem"></ReturnLine>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="optType != 'view'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <print-index ref="printindex" v-if="printvisible"></print-index>
  </div>
</template>

<script>
import {listReturn, getReturn, delReturn, addReturn, updateReturn,execute,confirmStatus } from "@/api/mes/rr/return";
import ReturnLine from "./returnline.vue"
import RepairSelect from "@/views/mes/rr/rreturn/repairselect.vue"
import {genCode} from "@/api/system/autocode/rule";
import PrintIndex from "@/views/mes/rr/rreturn/printindex";
export default {
  name: "Requisition",
  components: {PrintIndex, ReturnLine,RepairSelect},
  dicts: ['mes_order_status'],
  data() {
    return {
      printvisible:false,
      optType:undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 返修退料表格数据
      requisitionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,        orderName: null,        repairCode: null,        tenantId: null      },
      // 表单参数
      form: {
        lineList:[]
      },
      // 表单校验
      rules: {
        orderCode: [
          { required: true, message: "退料单编号不能为空", trigger: "blur" }
        ],
        orderName: [
          { required: true, message: "退料单名称不能为空", trigger: "blur" }
        ],
        repairCode: [
          { required: true, message: "返修单不能为空", trigger: "blur" }
        ],
        orderDate: [
          { required: true, message: "退料日期不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询返修退料列表 */
    getList() {
      this.loading = true;
      listReturn(this.queryParams).then(response => {
        this.requisitionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleView(row){
      const orderId = row.orderId
      getReturn(orderId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "查看退料单信息";
          this.optType = "view";
        });

    },
    handlePrint(row) {
      this.printvisible = true
      this.$nextTick(() => {
        this.$refs.printindex.init(row.orderId)
      })
    },
    //确认
    handleConfirme(row){
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('确认返工退料？').then(function () {
        return confirmStatus(orderIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("确认成功");
      }).catch(() => {
      });
    },
    //执行出库
    handleExecute(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('确认执行退料出库？').then(function () {
        return execute(orderIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("出库成功");
      }).catch(() => {
      });
    },
    // 表单重置
    reset() {
      this.form.lineList=[]
      this.form = {
        orderId: null,        orderCode: null,        orderName: null,        repairId: null,
        repairCode: null,        orderDate: new Date().toISOString().split('T')[0],        status: 'PREPARE',
        applicantUserId: null,        applicantUserName: null,        deptId: null,        deptName: null,
        remark: null,        createTime: null,        createBy: null,        createByName: null,
        updateTime: null,        updateBy: null,        tenantId: null      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('RR_RETURN_MATERIAL_CODE').then(response =>{
        this.form.orderCode = response;
      });
      this.open = true;
      this.title = "添加返修退料";
      this.optType="add"

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getReturn(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改返修退料";
        this.optType="edit"
      });
    },
    //选择生产工单
    handleRepairSelect(){
      this.$refs.repairSelect.showFlag = true;
    },
    onRepairSelected(row){
      if(row != undefined && row != null){
        this.form.repairId = row.id;
        this.form.repairCode = row.repairCode;
      }
    },
    getItem(lines){
      //接收单据体的数据
      console.log("aaaaaaaaaaaaaa",lines)
      this.form.lineList=[]
      this.form.lineList=lines

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
  /*    console.log("ttttt",this.$refs.line.requisitionlineList)
      this.$refs.line.requisitionlineList*/
/*      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateReturn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReturn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });*/

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除返修退料编号为"' + orderIds + '"的数据项？').then(function() {
        return delReturn(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rr/requisition/export', {
        ...this.queryParams
      }, `requisition_${new Date().getTime()}.xlsx`)
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('RR_RETURN_MATERIAL_CODE').then(response =>{
          this.form.orderCode = response;
        });
      }else{
        this.form.orderCode = null;
      }
    },

  }
};
</script>
